/**
 * 画布对象内容显示面板
 * 显示画布对象中的所有元件列表，支持点击聚焦到特定元件
 */
import { CircuitElement } from '../circuit-elements.js';

export class CanvasContentPanel {
    private container: HTMLElement;
    private panel!: HTMLElement;
    private isVisible: boolean = false;
    private canvasManager: any;
    private elementsList!: HTMLElement;

    constructor(container: HTMLElement, canvasManager: any) {
        this.container = container;
        this.canvasManager = canvasManager;
        this.createPanel();
        this.setupEventListeners();
    }

    private createPanel(): void {
        // 创建主面板容器
        this.panel = document.createElement('div');
        this.panel.id = 'canvas-content-panel';
        this.panel.style.cssText = `
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 250px;
            max-height: 500px;
            background: white;
            border: 1px solid #ccc;
            border-radius: 0 8px 8px 0;
            box-shadow: 2px 0 8px rgba(0,0,0,0.1);
            z-index: 1000;
            display: flex;
            flex-direction: column;
            font-family: Arial, sans-serif;
            font-size: 14px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            transform: translateX(-220px) translateY(-50%);
        `;

        // 创建折叠标签（始终可见的小标签）
        const tab = document.createElement('div');
        tab.id = 'panel-tab';
        tab.style.cssText = `
            position: absolute;
            right: -30px;
            top: 50%;
            transform: translateY(-50%);
            width: 30px;
            height: 80px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 0 8px 8px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: white;
            font-size: 12px;
            font-weight: bold;
            writing-mode: vertical-rl;
            text-orientation: mixed;
            box-shadow: 2px 2px 6px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        `;
        tab.textContent = '元件列表';
        tab.title = '点击展开/折叠元件列表';

        // 添加标签悬停效果
        tab.addEventListener('mouseenter', () => {
            tab.style.background = 'linear-gradient(135deg, #764ba2 0%, #667eea 100%)';
            tab.style.boxShadow = '2px 2px 10px rgba(0,0,0,0.3)';
            tab.style.width = '35px';
        });

        tab.addEventListener('mouseleave', () => {
            if (!this.isVisible) {
                tab.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
                tab.style.boxShadow = '2px 2px 6px rgba(0,0,0,0.2)';
                tab.style.width = '30px';
            }
        });

        // 标签点击事件
        tab.addEventListener('click', () => {
            this.toggle();
        });

        this.panel.appendChild(tab);

        // 创建面板头部
        const header = document.createElement('div');
        header.style.cssText = `
            padding: 12px 16px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 1px solid #ddd;
            border-radius: 0 8px 0 0;
            font-weight: bold;
            color: #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        `;
        header.innerHTML = `
            <span>画布元件列表</span>
            <button id="close-panel-btn" style="
                background: none;
                border: none;
                font-size: 16px;
                cursor: pointer;
                color: #666;
                padding: 4px;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 50%;
                transition: all 0.2s ease;
            ">×</button>
        `;

        // 关闭按钮悬停效果
        const closeBtn = header.querySelector('#close-panel-btn') as HTMLButtonElement;
        closeBtn.addEventListener('mouseenter', () => {
            closeBtn.style.background = '#e9ecef';
            closeBtn.style.color = '#333';
        });
        closeBtn.addEventListener('mouseleave', () => {
            closeBtn.style.background = 'none';
            closeBtn.style.color = '#666';
        });

        // 创建元件列表容器
        this.elementsList = document.createElement('div');
        this.elementsList.style.cssText = `
            flex: 1;
            overflow-y: auto;
            padding: 8px;
            background: white;
        `;

        // 创建面板底部
        const footer = document.createElement('div');
        footer.style.cssText = `
            padding: 8px 16px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-top: 1px solid #ddd;
            border-radius: 0 0 8px 0;
            font-size: 12px;
            color: #666;
            flex-shrink: 0;
        `;

        // 组装面板
        this.panel.appendChild(header);
        this.panel.appendChild(this.elementsList);
        this.panel.appendChild(footer);
        this.container.appendChild(this.panel);

        // 设置关闭按钮事件
        closeBtn.addEventListener('click', () => this.hide());

        // 设置面板悬停事件 - 鼠标移入时自动展开
        this.panel.addEventListener('mouseenter', () => {
            if (!this.isVisible) {
                this.show();
            }
        });

        // 设置面板离开事件 - 鼠标移出时自动折叠（延迟）
        this.panel.addEventListener('mouseleave', (e) => {
            // 检查鼠标是否真的离开了面板区域
            const rect = this.panel.getBoundingClientRect();
            const mouseX = e.clientX;
            const mouseY = e.clientY;
            
            // 如果鼠标在面板外，延迟折叠
            if (mouseX < rect.left || mouseX > rect.right || mouseY < rect.top || mouseY > rect.bottom) {
                setTimeout(() => {
                    // 再次检查鼠标位置，确保用户没有快速移回
                    const currentRect = this.panel.getBoundingClientRect();
                    if (mouseX < currentRect.left || mouseX > currentRect.right || 
                        mouseY < currentRect.top || mouseY > currentRect.bottom) {
                        this.hide();
                    }
                }, 300);
            }
        });
    }

    private setupEventListeners(): void {
        // 监听元件添加事件
        window.addEventListener('circuit-editor:element-added', () => {
            if (this.isVisible) {
                this.updateElementsList();
            }
        });

        // 监听键盘快捷键 (Ctrl/Cmd + Shift + C)
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
                e.preventDefault();
                this.toggle();
            }
        });

        // 初始状态：面板是折叠的，但标签始终可见
        this.hide();
    }

    public show(): void {
        this.isVisible = true;
        this.panel.style.transform = 'translateX(0) translateY(-50%)';
        this.panel.style.boxShadow = '2px 0 12px rgba(0,0,0,0.15)';
        this.updateElementsList();
    }

    public hide(): void {
        this.isVisible = false;
        this.panel.style.transform = 'translateX(-220px) translateY(-50%)';
        this.panel.style.boxShadow = '2px 0 8px rgba(0,0,0,0.1)';
    }

    public toggle(): void {
        if (this.isVisible) {
            this.hide();
        } else {
            this.show();
        }
    }

    private updateElementsList(): void {
        const elements = this.canvasManager.getElements();
        this.elementsList.innerHTML = '';

        if (elements.length === 0) {
            this.elementsList.innerHTML = `
                <div style="
                    padding: 20px;
                    text-align: center;
                    color: #999;
                    font-style: italic;
                ">
                    画布中暂无元件
                </div>
            `;
            return;
        }

        // 按类型分组元件
        const elementsByType = this.groupElementsByType(elements);

        Object.entries(elementsByType).forEach(([type, typeElements]) => {
            // 创建类型标题
            const typeHeader = document.createElement('div');
            typeHeader.style.cssText = `
                padding: 8px 12px;
                background: #e9ecef;
                border-radius: 4px;
                margin: 4px 0;
                font-weight: bold;
                color: #495057;
                font-size: 13px;
            `;
            typeHeader.textContent = this.getTypeDisplayName(type);
            this.elementsList.appendChild(typeHeader);

            // 创建该类型的元件列表
            typeElements.forEach((element, index) => {
                const elementItem = document.createElement('div');
                elementItem.style.cssText = `
                    padding: 10px 12px;
                    margin: 2px 0;
                    background: white;
                    border: 1px solid #e0e0e0;
                    border-radius: 4px;
                    cursor: pointer;
                    transition: all 0.2s ease;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                `;

                elementItem.innerHTML = `
                    <div>
                        <div style="font-weight: 500; color: #333;">
                            ${this.getElementDisplayName(element)}
                        </div>
                        <div style="font-size: 11px; color: #666; margin-top: 2px;">
                            ID: ${element.id.substring(0, 8)}...
                        </div>
                        <div style="font-size: 11px; color: #888;">
                            位置: (${Math.round(element.position.x)}, ${Math.round(element.position.y)})
                        </div>
                    </div>
                    <div style="
                        width: 8px;
                        height: 8px;
                        background: #28a745;
                        border-radius: 50%;
                        flex-shrink: 0;
                    "></div>
                `;

                // 鼠标悬停效果
                elementItem.addEventListener('mouseenter', () => {
                    elementItem.style.background = '#f8f9fa';
                    elementItem.style.borderColor = '#007bff';
                    elementItem.style.transform = 'translateX(2px)';
                });

                elementItem.addEventListener('mouseleave', () => {
                    elementItem.style.background = 'white';
                    elementItem.style.borderColor = '#e0e0e0';
                    elementItem.style.transform = 'translateX(0)';
                });

                // 点击事件：聚焦到元件
                elementItem.addEventListener('click', () => {
                    this.focusOnElement(element);
                });

                this.elementsList.appendChild(elementItem);
            });
        });

        // 更新底部统计信息
        const footer = this.panel.querySelector('div:last-child') as HTMLElement;
        footer.textContent = `共 ${elements.length} 个元件`;
    }

    private groupElementsByType(elements: CircuitElement[]): Record<string, CircuitElement[]> {
        const grouped: Record<string, CircuitElement[]> = {};
        
        elements.forEach(element => {
            const type = element.type || 'unknown';
            if (!grouped[type]) {
                grouped[type] = [];
            }
            grouped[type].push(element);
        });

        return grouped;
    }

    private getTypeDisplayName(type: string): string {
        const typeNames: Record<string, string> = {
            'resistor': '电阻',
            'capacitor': '电容',
            'inductor': '电感',
            'voltage_source': '电压源',
            'current_source': '电流源',
            'wire': '导线',
            'ground': '接地',
            'unknown': '未知元件'
        };
        return typeNames[type] || type;
    }

    private getElementDisplayName(element: CircuitElement): string {
        const baseName = this.getTypeDisplayName(element.type || 'unknown');
        
        // 根据元件类型添加特定信息
        switch (element.type) {
            case 'resistor':
                return `${baseName} (${(element as any).properties?.resistance || 1000}Ω)`;
            case 'capacitor':
                return `${baseName} (${(element as any).properties?.capacitance || 1e-6}F)`;
            case 'voltage_source':
                return `${baseName} (${(element as any).properties?.voltage || 5}V)`;
            case 'current_source':
                return `${baseName} (${(element as any).properties?.current || 0.1}A)`;
            case 'wire':
                return `${baseName} (${Math.round((element as any).properties?.length || 50)}px)`;
            default:
                return baseName;
        }
    }

    private focusOnElement(element: CircuitElement): void {
        // 将元件居中显示在画布显示区域
        this.canvasManager.centerOnElement(element);
        
        // 高亮显示元件（临时效果）
        this.highlightElement(element);
    }

    private highlightElement(element: CircuitElement): void {
        // 查找元件的DOM元素
        const elementDOM = document.querySelector(`[data-element-id="${element.id}"]`) as SVGGElement;
        if (!elementDOM) return;

        // 创建高亮效果
        const originalFilter = elementDOM.style.filter;
        const originalTransform = elementDOM.getAttribute('transform');

        // 添加发光效果
        elementDOM.style.filter = 'drop-shadow(0 0 8px rgba(255, 193, 7, 0.8))';
        elementDOM.style.transition = 'filter 0.3s ease';

        // 添加脉冲动画
        let scale = 1;
        let growing = true;
        const animationInterval = setInterval(() => {
            if (growing) {
                scale += 0.02;
                if (scale >= 1.1) growing = false;
            } else {
                scale -= 0.02;
                if (scale <= 1) growing = true;
            }
            
            const baseTransform = originalTransform || `translate(${element.position.x}, ${element.position.y})`;
            elementDOM.setAttribute('transform', `${baseTransform} scale(${scale})`);
        }, 50);

        // 3秒后移除高亮效果
        setTimeout(() => {
            clearInterval(animationInterval);
            elementDOM.style.filter = originalFilter;
            elementDOM.setAttribute('transform', originalTransform || '');
            elementDOM.style.transition = '';
        }, 3000);
    }
}